<template>
  <div class="container">
    <div class="layout">
      <div class="layout-left-side">
        <t-card>
          <t-row style="margin-bottom: 16px">
            <t-col :span="16">
              <t-space>
                <t-button v-permission="authority.SYS_DICT_ADD" theme="primary" @click="add">
                  <template #icon><add-icon /></template>
                  新建
                </t-button>
              </t-space>
            </t-col>
          </t-row>
          <t-table
            :data="renderData"
            :columns="columns"
            row-key="id"
            :hover="true"
            :pagination="pagination"
            :loading="loading"
            table-layout="auto"
            size="small"
            @page-change="pageChange"
            @row-dblclick="rowClick"
          >
            <template #operations="{ row }">
              <t-button
                v-permission="authority.SYS_DICT_EDIT"
                variant="text"
                size="small"
                theme="primary"
                @click="edit(row)"
              >
                <template #icon><edit-icon /></template>
                编辑
              </t-button>
              <t-popconfirm
                :content="`此操作将永久删除(${row.description}), 是否继续?`"
                type="warning"
                @confirm="del(row.id)"
              >
                <t-button v-permission="authority.SYS_DICT_DEL" variant="text" size="small" theme="danger">
                  <template #icon>
                    <delete-icon />
                  </template>
                  删除
                </t-button>
              </t-popconfirm>
            </template>
          </t-table>
        </t-card>
      </div>

      <div class="layout-right-side">
        <t-card>
          <t-row style="margin-bottom: 16px">
            <t-col :span="16">
              <t-space v-if="chooseDict">
                <t-button v-permission="authority.SYS_DICT_ADD" theme="primary" @click="addItem">
                  <template #icon><add-icon /></template>
                  新建
                </t-button>
                <t-space>
                  <t-tag size="large">{{ chooseDict.description }}</t-tag>
                  <t-tag size="large">{{ chooseDict.type }}</t-tag>
                </t-space>
              </t-space>
            </t-col>
          </t-row>
          <t-table
            :data="itemRenderData"
            :columns="itemColumns"
            row-key="id"
            :hover="true"
            :pagination="itemPagination"
            :loading="itemLoading"
            table-layout="auto"
            size="small"
            @page-change="itemPageChange"
          >
            <template #operations="{ row }">
              <t-button
                v-permission="authority.SYS_DICT_EDIT"
                variant="text"
                size="small"
                theme="primary"
                @click="editItem(row)"
              >
                <template #icon><edit-icon /></template>
                编辑
              </t-button>
              <t-popconfirm
                :content="`此操作将永久删除(${row.label}), 是否继续?`"
                theme="warning"
                @confirm="delItem(row.id)"
              >
                <t-button v-permission="authority.SYS_DICT_DEL" variant="text" size="small" theme="danger">
                  <template #icon>
                    <delete-icon />
                  </template>
                  删除
                </t-button>
              </t-popconfirm>
            </template>
          </t-table>
        </t-card>
      </div>
    </div>
    <dict-form v-model:visible="formDialogVisible" :form-data="formData" @refresh="refresh" />
    <dict-item-form
      v-model:visible="itemFormDialogVisible"
      :form-data="itemFormData"
      :dict="chooseDict"
      @refresh="itemRefush"
    />
  </div>
</template>

<script lang="ts" setup>
import { AddIcon, DeleteIcon, EditIcon } from 'tdesign-icons-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { computed, ref } from 'vue';
import { usePagination } from 'vue-request';

import { deleteDict, deleteDictItem, dictItemPage, dictPage } from '@/api/upms/dict';
import authority from '@/utils/authority';
import defaultPageOptions from '@/utils/pagination';

import DictForm from './components/dict-form.vue';
import DictItemForm from './components/dict-item-form.vue';

const { data, loading, refresh, current, pageSize, total } = usePagination(dictPage, {
  ...defaultPageOptions,
});

const renderData = computed(() => data.value?.records || []);

const formData = ref();

const pagination = computed(() => ({
  current: current.value,
  pageSize: pageSize.value,
  showTotal: true,
  showPageSize: true,
  total: total.value,
}));

const columns = [
  { title: '类型', colKey: 'type' },
  {
    title: '描述',
    colKey: 'description',
  },
  { title: '创建时间', colKey: 'createTime' },
  { title: '操作', colKey: 'operations' },
];

const {
  data: itemData,
  loading: itemLoading,
  refresh: itemRefush,
  current: itemCurrent,
  pageSize: itemPageSize,
  total: itemTotal,
  runAsync: itemRunAsync,
} = usePagination((params) => dictItemPage(params), {
  ...defaultPageOptions,
  manual: true,
});

const itemRenderData = computed(() => itemData.value?.records || []);

const itemFormData = ref();

const itemPagination = computed(() => ({
  current: itemCurrent.value,
  pageSize: itemPageSize.value,
  showTotal: true,
  showPageSize: true,
  total: itemTotal.value,
}));

const itemColumns = [
  { title: '数据值', colKey: 'value' },
  {
    title: '标签名',
    colKey: 'label',
  },
  { title: '排序', colKey: 'sort' },
  { title: '描述', colKey: 'description' },
  {
    title: '操作',
    colKey: 'operations',
  },
];
// 弹出框标记
const formDialogVisible = ref(false);

// 弹出框标记
const itemFormDialogVisible = ref(false);

// 选择的列ID
const chooseDict = ref();

const rowClick = ({ row }: { row: any }) => {
  chooseDict.value = row;
  itemRunAsync({ dictId: row.id });
};

const add = () => {
  formData.value = {};
  formDialogVisible.value = true;
};
const edit = (e: any) => {
  formDialogVisible.value = true;
  formData.value = { ...e };
};
const del = async (id: string) => {
  await deleteDict(id).then(() => {
    MessagePlugin.success('删除成功');
    refresh();
    itemRefush();
    chooseDict.value = {};
  });
};

const addItem = () => {
  itemFormData.value = {};
  itemFormDialogVisible.value = true;
};
const editItem = (e: any) => {
  itemFormDialogVisible.value = true;
  itemFormData.value = { ...e };
};
const delItem = async (id: string) => {
  await deleteDictItem(id).then(() => {
    MessagePlugin.success('删除成功');
    itemRefush();
  });
};

const pageChange = (curr: any) => {
  if (pageSize.value !== curr.pageSize) {
    pageSize.value = curr.pageSize;
  }
  if (current.value !== curr.current) {
    current.value = curr.current;
  }
};

const itemPageChange = (curr: any) => {
  if (itemPageSize.value !== curr.pageSize) {
    itemPageSize.value = curr.pageSize;
  }
  if (itemCurrent.value !== curr.current) {
    itemCurrent.value = curr.current;
  }
};
</script>

<style scoped lang="less">
.container {
  padding: 0px 10px 0px 10px;
}
.layout {
  display: flex;

  &-left-side {
    flex: 1;
  }

  &-right-side {
    margin-left: 10px;
    flex: 1;
  }
}
</style>
